import fs from 'fs';
import jwt from 'jsonwebtoken';
import { v4 as uuidv4 } from 'uuid';
// import { secretKey } from './config';
import express from 'express';
import multer from 'multer';
import path from 'path';
import { fileURLToPath } from 'url';
const secretKey = 'your_secret_key';
const user = express.Router();

user.get('/getPermissionList', (req, res) => {
  // 获取请求头中的 token
  const token = req.headers['authorization'];
  if (!token) {
    return res.json({
      success: false,
      code: 401,
      message: '未登录',
      data: null
    });
  }
  const menus = JSON.parse(fs.readFileSync('./data/menus.json', 'utf-8'));
  try {
    // 验证 token
    const userInfo = jwt.verify(token, secretKey);
    res.json({
      success: true,
      code: 100,
      message: '成功',
      data: {
        buttonList: menus.reduce((pre, cur) => {
          if (cur.type === 2) {
            pre.push(cur);
          }
          if(cur.children){
            pre.push(...cur.children.filter(item => item.type === 2));
          }
          return pre;
        }
          , []),
        menuList: menus
      }
    });
  } catch (error) {
    res.json({
      success: false,
      code: 401,
      message: '登录失效',
      data: null
    });
  }

});

user.get('/allUserList', (req, res) => {
  // 获取请求头中的 token
  const token = req.headers['authorization'];
  if (!token) {
    return res.json({
      success: false,
      code: 401,
      message: '未登录',
      data: null
    });
  }
  const users = JSON.parse(fs.readFileSync('./data/users.json', 'utf-8'));
  try {
    // 验证 token
    const userInfo = jwt.verify(token, secretKey);
    res.json({
      success: true,
      code: 100,
      message: '成功',
      data: users
    });
  } catch (error) {
    res.json({
      success: false,
      code: 401,
      message: '登录失效',
      data: null
    });
  }

});
user.get('/userList', (req, res) => {
  // 获取请求头中的 token
  const token = req.headers['authorization'];
  const { pageNum = 1, pageSize = 10 } = req.query;
  if (!token) {
    return res.json({
      success: false,
      code: 401,
      message: '未登录',
      data: null
    });
  }
  const users = JSON.parse(fs.readFileSync('./data/users.json', 'utf-8'));
  try {
    // 验证 token
    const userInfo = jwt.verify(token, secretKey);
    const { pageNum = 1, pageSize = 10 } = req.query;
    const start = (pageNum - 1) * pageSize;
    const end = start + pageSize;
    res.json({
      success: true,
      code: 100,
      message: '成功',
      data: {
        total: users.length,
        list: users.slice(start, end)
      }
    });
  } catch (error) {
    res.json({
      success: false,
      code: 401,
      message: '登录失效',
      data: null
    });
  }

});
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads');
  },
  filename: function (req, file, cb) {
    const { originalname } = file;
    cb(null, originalname);
  }
});
const upload = multer({ storage });

user.post('/upload', upload.single('file'), (req, res) => {
  console.log('req.file:', req.file);
  // 获取请求头中的 token
  // const token = req.headers['authorization'];
  // if (!token) {
  //   return res.json({
  //     success: false,
  //     code: 401,
  //     message: '未登录',
  //     data: null
  //   });
  // }
  res.json({
    success: true,
    code: 100,
    message: '上传成功',
    data: {
      url: `http://localhost:3000/uploads/${req.file.originalname}`
    }
  });

});
// 获取当前文件的文件名和目录名
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); // 获取当前文件的目录名src
console.log('__filename:', __filename);
console.log('__dirname:', __dirname);//
// 设置静态文件目录 uploads和src同级
user.use('/uploads', express.static(path.join(__dirname, '../uploads')));

// 创建编辑用户，数据存放到data/users文件中
user.post('/update', (req, res) => {
  const users = JSON.parse(fs.readFileSync('./data/users.json', 'utf-8'));

  const { id, username, email, ...otherInfo } = req.body;
  if (!username || !email) {
    return res.status(400).json({ message: '用户名和邮箱不能为空' });
  }
  // 编辑用户
  if (id) {
    const user = users.find(user => user.id === id);
    if (!user) {
      return res.status(404).json({ code: 10000, success: false, message: '用户不存在' });
    }
    const userUpdate = { ...user, username, email, ...otherInfo };
    users.splice(users.findIndex(user => user.id === id), 1, userUpdate);
    fs.writeFileSync('./data/users.json', JSON.stringify(users, null, 2), 'utf-8');  // 将数据写入文件
    return res.json({ success: true, message: '更新用户成功' });
  }
  // 创建用户
  const user = { id: uuidv4(), username, email, ...otherInfo, createTime: new Date().getMilliseconds(), lastLoginTime: new Date().getMilliseconds() };
  users.push(user);
  fs.writeFileSync('./data/users.json', JSON.stringify(users, null, 2), 'utf-8');  // 将数据写入文件

  res.json({ success: true, message: '创建用户成功' });
});

// 删除用户
user.post('/delete', (req, res) => {
  const users = JSON.parse(fs.readFileSync('./data/users.json', 'utf-8'));

  const ids = req.body;
  const delId = (id) => {
    const index = users.findIndex(user => user.id === id);
    if (index === -1) {
      return res.json({ success: false, message: '用户不存在' });
    }
    users.splice(index, 1);
  }
  Array.isArray(ids) ? ids.forEach(delId) : delId(ids);
  fs.writeFileSync('./data/users.json', JSON.stringify(users, null, 2), 'utf-8');  // 将数据写入文件
  res.json({ success: true, message: '删除用户成功' });
});



export default user;